#!/usr/bin/python
# -*- coding:UTF-8 -*-


import os
import sys
import commands
import MySQLdb
import json


def cmd_output(command):
    (status, output) = commands.getstatusoutput(command)
    return status

def noeol_process(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path,file)) == True:
            f=open(os.path.join(path,file),'a+')       
#            print f
            f.write('\n')
            f.close()
#            print f
        else:
             continue
  

def rename_file(path):
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path,file)) == True:
            if file.find('.json') < 0:
                newname = file + '.json'
                os.rename(os.path.join(path,file),os.path.join(path,newname))
                print file,'Rename Is Ok'
            else:
                continue
        else:
            continue

def create_table_hosts(conn):

    sql = '''
--    CREATE TABLE if not exists cmdb_hosts
    CREATE TABLE cmdb_hosts
    (
     id  int PRIMARY KEY NOT NULL AUTO_INCREMENT,
     IP  CHAR(20) NOT NULL,
     hostname  CHAR(50),
     gateway CHAR(20),
     mac CHAR(30),
     distribution CHAR(50),
     distribution_version CHAR(50),
     architecture CHAR(20),
     kernel CHAR(30),
     processor CHAR(255),
     processor_cores CHAR(20),
     processor_count CHAR(20),
     memory CHAR(20),
     oracle_version CHAR(20),
     mysql_version CHAR(20),
     python_version CHAR(20),
     jboss_version CHAR(20)
    )
    '''

    try:
        cur = conn.cursor()
        print "[ Create Table ] -- MySQL Cursor Open."
        cur.execute(sql)
        print "[ Create Table ] -- Table Created."
    except Exception as e:
        print "[ Create Table ][ Warning ] -- %s" % e
    finally:
        cur.close()
        print "[ Create Table ] -- MySQL Cursor Close."

def setup_update(conn,setup_temp_dir,setup_temp_list):
    try:
        cur = conn.cursor()
        print "[ Update or Insert Data - Setup ] -- MySQL Cursor Open."

        file = open(setup_temp_list,"r")

        if file:
            for line in file:
                fact = line.strip('\n')
                print "[ Update or Insert Data - Setup ] -- %s is Processing." % fact

                file_fact = open(setup_temp_dir+'/'+fact,"r")

                if file_fact:
                    try:
                        data = json.loads(file_fact.read())
                        system = data['ansible_facts']['ansible_system']
#                        print system
                        if system == 'HP-UX':
                            gateway = data['ansible_facts']['ansible_default_gateway']
                            processor = data['ansible_facts']['ansible_processor']
                            mac = ""
                            python_version = data['ansible_facts']['ansible_python_version']
                            architecture = data['ansible_facts']['ansible_architecture']
                        elif system == 'Linux':
                            gateway = data['ansible_facts']['ansible_default_ipv4']['gateway']
                            processor = "-".join(data['ansible_facts']['ansible_processor'])
                            mac = data['ansible_facts']['ansible_default_ipv4']['macaddress']
                            python_version = data['ansible_facts']['ansible_python_version']
                            architecture = data['ansible_facts']['ansible_architecture']
                        elif system == 'Win32NT':
                            gateway = data['ansible_facts']['ansible_interfaces'][0]['default_gateway']
#                            print gateway
                            processor = data['ansible_facts']['ansible_processor']
#                            print processor
                            mac = data['ansible_facts']['ansible_interfaces'][0]['macaddress']
                            python_version = ""
#                            print mac
#                       print data
                        hostname = data['ansible_facts']['ansible_hostname']
#                       print hostname
                        IP = fact
                        distribution = data['ansible_facts']['ansible_distribution']
                        distribution_version = data['ansible_facts']['ansible_distribution_version']
                        kernel = data['ansible_facts']['ansible_kernel']
                        processor_cores = data['ansible_facts']['ansible_processor_cores']
                        processor_count = data['ansible_facts']['ansible_processor_count']
                        memory = data['ansible_facts']['ansible_memtotal_mb']
#                        print python_version
#                        print hostname,architecture,distribution,distribution_version,kernel,IP,gateway,mac,processor,python_version
                    except Exception as e:
                        sql=""
                        print "[ Update or Insert Data - Setup ][ Warning ] -- %s is Skipped." % fact
                        continue

                check_host = "select * from cmdb_hosts where IP = '%s' " % (IP)
                flag = cur.execute(check_host)
#                print (flag,type(flag))

                if flag != 0L:
                    sql = "\
                    update cmdb_hosts set \
                    IP = '%s',\
                    hostname = '%s',\
                    gateway = '%s',\
                    mac = '%s',\
                    distribution = '%s',\
                    distribution_version = '%s',\
                    architecture = '%s',kernel = '%s',\
                    processor = '%s',\
                    processor_cores = '%s',\
                    processor_count = '%s',\
                    memory = '%s',\
                    python_version = '%s'\
                    where IP = '%s'\
                    " % (
                     IP,\
                     hostname,\
                     gateway,\
                     mac,\
                     distribution,\
                     distribution_version,\
                     architecture,\
                     kernel,\
                     processor,\
                     processor_cores,\
                     processor_count,\
                     memory,\
                     python_version,\
                     IP
                    )

                else:
                    sql = "\
                    insert into cmdb_hosts \
                    (\
                     IP,\
                     hostname,\
                     gateway,\
                     mac,\
                     distribution,\
                     distribution_version,\
                     architecture,\
                     kernel,\
                     processor,\
                     processor_cores,\
                     processor_count,\
                     memory,\
                     python_version\
                    ) values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')\
                    " % (
                     IP,\
                     hostname,\
                     gateway,\
                     mac,\
                     distribution,\
                     distribution_version,\
                     architecture,\
                     kernel,\
                     processor,\
                     processor_cores,\
                     processor_count,\
                     memory,\
                     python_version\
                    )
            
#                print sql
                try:
                    cur.execute(sql)
                    conn.commit()
                    print "[ Update or Insert Data - Setup ] -- %s update successfully." % IP
                except Exception as e:
                    conn.rollback()
#                    print "what???"
                    print "[ Update or Insert Data - Setup ][ Warning ] -- Rollbacked. %s" % e
                finally:
                    file_fact.close()

    except Exception as e:
        print "[ Update or Insert Data - Setup ][ Warning ] -- %s" % e
    finally:
        file.close()
        cur.close()
        print "[ Update or Insert Data - Setup ] -- MySQL Cursor Close."

def get_facts_update(conn,get_facts_temp_dir,get_facts_temp_list):
    try:
        cur = conn.cursor()
        print "[ Update or Insert Data - Get_Facts ] -- MySQL Cursor Open."

        file = open(get_facts_temp_list,"r")
#        print file

        if file:
            for line in file:
                fact = line.strip('\n')
                print "[ Update or Insert Data - Get_Facts ] -- %s is Processing." % fact

                file_fact = open(get_facts_temp_dir+'/'+fact,"r")
#                print file_fact
                if file_fact:
#                    data = json.loads(file_fact.read())
#                    print data
                    try:
                        data = json.loads(file_fact.read())
#                        print data
                        oracle_version = data['oracle_version']
                        jboss_version = data['jboss_version']
                        mysql_version = data['mysql_version']
                        IP = fact.split('.json')[0]
#                        print oracle_version,jboss_version,mysql_version,python_version,IP
                    except Exception as e:
                        sql=""
                        print "[ Update or Insert Data - Get_Facts ][ Warning ] -- %s is Skipped. %s" % (fact,e)
                        continue
                    
#                    print IP,oracle_version,jboss_version,mysql_version,python_version
                check_host = "select * from cmdb_hosts where IP = '%s' " % (IP)
                flag = cur.execute(check_host)

                if flag != 0L:
                    sql = "\
                    update cmdb_hosts set \
                    oracle_version = '%s',\
                    jboss_version = '%s',\
                    mysql_version = '%s'\
                    where IP = '%s'\
                    " % (\
                     oracle_version,\
                     jboss_version,\
                     mysql_version,\
                     IP\
                    )

                else:
                    sql = "\
                    insert into cmdb_hosts \
                    (\
                     IP,\
                     oracle_version,\
                     jboss_version,\
                     mysql_version\
                    ) values ('%s','%s','%s','%s')\
                    " % (\
                     IP,\
                     oracle_version,\
                     jboss_version,\
                     mysql_version\
                    )
#                print sql
                try:
                    cur.execute(sql)
                    conn.commit()
                    print "[ Update or Insert Data - Get_Facts ] -- %s update successfully." % IP
                except Exception as e:
                    conn.rollback()
                    print "[ Update or Insert Data - Get_Facts ][ Warning ] -- Rollbacked. %s" % e
                finally:
                    file_fact.close()

    except Exception as e:
        print "[ Update or Insert Data - Get_Facts ][ Warning ] -- %s" % e
    finally:
        file.close()
        cur.close()
        print "[ Update or Insert Data - Get_Facts ] -- MySQL Cursor Close."
    

def main():
    setup_temp_dir='/tmp/setup_hosts'
    setup_temp_list='/tmp/setup_list'
    get_facts_temp_dir='/tmp/get_facts_hosts'
    get_facts_temp_list='/tmp/get_facts_list'

    try:
#        conn = MySQLdb.connect("localhost","root","Password01","test",unix_socket='/mysql/app/mysql.sock')
        conn = MySQLdb.connect("localhost","root","Password01!","test")
        print ".......................... Start -- MySQL Connected .........................."
        command_out_setup='ansible all -m setup --tree ' +  setup_temp_dir
#        print command_out
        command_list_setup='ls %s > %s' % (setup_temp_dir,setup_temp_list)
#        print command_list
        setup_out_status=cmd_output(command_out_setup)
#        print setup_out_status
        (status, output) = commands.getstatusoutput('ansible all -m setup --tree /tmp/setup_hosts')
#        print status
        if ~setup_out_status:
            setup_list_status=cmd_output(command_list_setup)
#           print setup_list_status
            if ~setup_list_status:
                noeol_process(setup_temp_dir)
                create_table_hosts(conn)
                setup_update(conn,setup_temp_dir,setup_temp_list)

        command_out_get_facts='ansible all -m get_facts --tree ' + get_facts_temp_dir
        command_list_get_facts='ls %s > %s' % (get_facts_temp_dir,get_facts_temp_list)
        get_facts_out_status=cmd_output(command_out_get_facts)
        if ~get_facts_out_status:
            get_facts_list_status=cmd_output(command_list_get_facts)
            if ~get_facts_list_status:
#                create_table_hosts(conn)
                noeol_process(get_facts_temp_dir)
                get_facts_update(conn,get_facts_temp_dir,get_facts_temp_list)

    except Exception as e:
        print(e)

    finally:
        conn.close()
        print "....................... Finished -- MySQL Disconnected ......................."

if __name__=='__main__':
    main()
